from flask import Flask, jsonify, Response
from api.ACHBuild import evidence_bp
from utils.constants import SUCCESS_CODE, ERROR_CODE
from errors import BaseError


class NewFlask(Flask):

    def make_response(self, rv):
        if isinstance(rv, dict) or isinstance(rv, list):
            resp = jsonify({"code": SUCCESS_CODE, "msg": 'ok', "data": rv})
        elif isinstance(rv, str) or isinstance(rv, Response) or isinstance(rv, tuple):
            resp = rv
        else:
            raise BaseError(code=ERROR_CODE, msg='response error', http_code=500)
        return Flask.make_response(self, resp)


def create_app():
    app = NewFlask(__name__)
    app.register_blueprint(evidence_bp, url_prefix='/evidence')

    @app.errorhandler(BaseError)
    def error_handler(e):
        if isinstance(e, BaseError):
            return jsonify(code=e.code, msg=e.msg), e.http_code
        return jsonify(code=ERROR_CODE, msg=str(e)), 500

    return app
